<?php
class ModelManagementUser extends Model {
	
	public function getTotalUsers($data = array()) {
		$sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "user";
		
		$implode = array();
		
		if($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}
		
		$query = $this->db->query($sql);
		
		return $query->row['total'];
	}
	
	
	public function getUsers($data = array()) {
		$sql = "SELECT *, CONCAT(u.firstname, ' ', u.middlename, ' ',u.lastname) AS fullname FROM " . DB_PREFIX . "user u";
		
		$implode = array();
		
		if(!empty($data['filter_fullname'])) {
			$implode[] = "LCASE(CONCAT(u.firstname, ' ', u.middlename, ' ', u.lastname)) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_fullname'])) . "%'";
		}
		
		if(!empty($data['filter_email'])) {
			$implode[] = "LCASE(u.email) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_email'])) . "%'";
		}
		
		if(isset($data['filter_status']) && !is_null($data['filter_status'])) {
			$implode[] = "u.status = '" . (int)$data['filter_status'] . "'";
		}
		
		if(!empty($data['filter_date_added'])) {
			$implode[] = "DATE(u.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}
		
		if($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}
		
		$sort_data = array(
			'fullname',
			'u.email',
			'u.status',
			'u.date_added'
		);
		
		if(isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY fullname";
		}
		
		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}
		
		
		if(isset($data['start']) || isset($data['limit'])){
			if($data['start'] < 0){
				$data['start'] = 0;
			}
			
			if($data['limit'] < 1){
				$data['limit'] = 20;
			}
			
			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}
		
		$query = $this->db->query($sql);
		return $query->rows;
	}
}